
//
//  DDTOauthViewController.swift
//  weibo
//
//  Created by mac on 16/9/24.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit
import SVProgressHUD

class DDTOauthViewController: UIViewController {

   lazy var webView = UIWebView()
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "新浪微博"
        //设置导航栏
        setupNavigationBar()
        
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=" + client_id + "&redirect_uri=" + redirect_uri
//         print("urlStr = \(urlStr)")
        let url = NSURL(string: urlStr)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
        SVProgressHUD.showWithStatus("正在加载登录界面...")
        
    }
    
    //设置导航栏
    private func setupNavigationBar() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: .Plain, target: self, action: "autoInputAccountAndPassword")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: "carcelLogin")
        self.navigationItem.title = "登录"
        
    }
    
    /**
    *  填充账号和密码
    */
    func autoInputAccountAndPassword() -> Void {
    
          let jsCode = "document.getElementById('userId').value='1026272351@qq.com';document.getElementById('passwd').value='102596czy';"
        
        webView.stringByEvaluatingJavaScriptFromString(jsCode)
    }
    /**
     取消登陆
     */
    func carcelLogin() -> Void {
         SVProgressHUD.dismiss()
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    //下载界面完成,取消提示
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
        
    }

    //关闭授权界面
    func closeOauthView() {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    
}



/**
*  webView代理方法跟踪重定向URL
 "https://m.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330&from=844b&vit=fps&normalload=1"
 
 "https://m.baidu.com/?code=4d73320f89ed2593818c39e0c23ab178&from=844b&vit=fps&normalload=1"
*/
extension DDTOauthViewController: UIWebViewDelegate {
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL!.absoluteString
        print("urlString = \(urlString)")
        
        if !urlString.hasPrefix(redirect_uri) {
            return true
        }
        else {
            /// 问号后面的字符串  query
            let query = request.URL?.query
            print("query = \(query)")
            let codeString = "code="
            //
            if query!.hasPrefix(codeString) {
                //授权
                let nsQuery = query! as NSString
                let code = nsQuery.substringFromIndex(codeString.characters.count)
                print("code = \(code)")
                DDTUseAccountVC.shared.loadOauthAccessTokent(code, completion: { (error) -> Void in
                    if error != nil {
                        SVProgressHUD.showErrorWithStatus("授权失败")
                        return
                    }
                    SVProgressHUD.showSuccessWithStatus("成功授权")
                    
                    SVProgressHUD.showSuccessWithStatus("发布微博成功了")
                    // 延时关闭
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                        self.closeOauthView()
                    })
                    
                })
               
            }else {
                //取消
                closeOauthView()
                
            }
            return false
            
        }
        
    }
    
  
 
}


